<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>开关组件</title>
    <script src="https://unpkg.com/vue@next"></script>
  </head>
  <body>
    <div id="Application">
        <!--组件定义的属性为小写字母驼峰，在html中用“-”分割驼峰命名法 -->
      <my-switch @switch-change="change1" switch-style="mini" 
        background-color="green" border-color="green" color="blue"></my-switch>
      <div>开关状态:{{state1}}</div>
      <br/>
      <my-switch @switch-change="change2" switchStyle="normal" 
        background-color="blue" border-color="blue" color="red"></my-switch>
      <div>开关状态:{{state2}}</div>
      
    </div>
  </body>

  <script>
    const switchComponet = {
        props: ["switchStyle","borderColor","backgroundColor","color"],
        data(){
            return {
                isOpen:false,
                left:'0px'
            }
        },
        computed:{
            cssStyleBG: {
                get(){
                    if(this.switchStyle == 'mini') {
                        return `position: relative; border-color: ${this.borderColor}; border-width: 2px; border-style: solid; width: 55px; height: 30px; border-radius: 30px; background-color: ${this.isOpen ? this.backgroundColor: 'white'};`
                    }else{
                        return `position: relative; border-color: ${this.borderColor}; border-width: 2px; border-style: solid; width: 55px; height: 30px; border-radius: 10px; background-color: ${this.isOpen ? this.backgroundColor: 'white'};`
                    }
                }
            },
            cssStyleBtn: {
                get(){
                    if(this.switchStyle == 'mini') {
                        return `position: absolute; width: 30px; height: 30px; left: ${this.left}; border-radius: 50%; background-color: ${this.color};`
                    }else{
                        return `position: absolute; width: 30px; height: 30px; left: ${this.left}; border-radius: 8px; background-color: ${this.color};`
                    }
                }
            }
        },
        methods:{
            click(){
                this.isOpen = !this.isOpen
                this.left = this.isOpen ? '25px' : '0px'
                this.$emit('switchChange', this.isOpen)
            }
        },
        template: `
            <div :style="cssStyleBG" @click="click">
                <div :style="cssStyleBtn"></div>
            </div>`
    }
    const App = Vue.createApp({
        data(){
            return {
                state1:'关',
                state2:'关',
            }
        },
        methods:{
            change1(isOpen){
                this.state1 = isOpen? "开" : "关"
            },
            change2(isOpen){
                this.state2 = isOpen? "开" : "关"
            }
        }
    })
    App.component("my-switch", switchComponet)
    App.mount("#Application")
  </script>

</html>